package com.fy56.platform.logistics.interceptor;

import com.fy56.platform.logistics.redis.dbutil.TokenConstants;
import com.fy56.platform.logistics.service.common.IRedisService;
import com.fy56.platform.logistics.utils.ConfigUtil;
import com.fy56.platform.logistics.utils.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截指定path，进行权限验证，及用户的本地session过期后，重新进行赋值
 */
@SuppressWarnings("ALL")
public class LogisticsInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ConfigUtil configUtil;

    @Autowired
    private IRedisService iRedisService;

    private static final Logger logger = LoggerFactory.getLogger(LogisticsInterceptor.class);

    /**
     * 判断该用户是否已登录,如果没有登录,跳转到登录界面
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod hd = (HandlerMethod) handler;
        String methodName = hd.getMethod().getName();
        if("userLogin".equals(methodName)){
            return true;
        }

        if(SessionUtil.getSessionUser(request) == null){
            logger.info("登录验证：request为无效请求，登录失效！");
            return false;
        }
        //获取token
        String token = null;
        Cookie[] cookies = request.getCookies();
        if(null == cookies){
            logger.info("登录验证：cookie为空，登录失效！");
            return false;
        }
        for (Cookie cookie: cookies) {
            if ("token".equals(cookie.getName())) {
                token = cookie.getValue();
                break;
            }
        }

//        //从redis中检查该token是否存在
//        Object tokenValue = iRedisService.get(String.format(TokenConstants.TOKEN_PREFIX, token));
//        if (tokenValue == null || StringUtils.isEmpty(tokenValue)) {
//            logger.info("登录验证：Redis中查询不到token！");
//            return false;
//        }else {
//            logger.info("token：" + tokenValue);
//            return true;
//        }
        return true;
    }
}
